package com.gxa.o2o.core.validator;


import com.gxa.o2o.core.exception.BusinessException;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

@Component
public class MyValidator {

    /**
     * 验证器
     */
    private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 不带分组的校验
     *
     * @param obj
     */
    public void validate(Object obj) throws BusinessException {
        Set<ConstraintViolation<Object>> validate = validator.validate(obj);
        for (ConstraintViolation<Object> violation : validate) {
            throw new BusinessException(violation.getMessage());
        }
    }

    /**
     * 带分组的校验
     *
     * @param obj
     */
    public void validate(Object obj, Class<?> clazz) throws BusinessException {
        Set<ConstraintViolation<Object>> validate = validator.validate(obj, clazz);
        for (ConstraintViolation<Object> violation : validate) {
            throw new BusinessException(violation.getMessage());
        }
    }
}
